package com.runen.infinitemovement.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import com.runen.infinitemovement.R;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.entity.ADDataEntity;
import com.runen.infinitemovement.model.entity.AdInfoEntity;
import com.runen.infinitemovement.model.entity.GetTopIdEntity;
import com.runen.infinitemovement.model.entity.JudgeBranchCheckEntity;
import com.runen.infinitemovement.steputil.StepService;
import com.runen.infinitemovement.tool.ADToWebOrActivityUtil;
import com.runen.infinitemovement.tool.AppUtils;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.DeviceUtils;
import com.runen.rxnetlibrary.utils.LogUtil;
import com.runen.rxnetlibrary.utils.SharePreferenceUtils;
import com.runen.rxnetlibrary.utils.ToastUtils;

import java.util.HashSet;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.net.shoot.sharetracesdk.AppData;
import cn.net.shoot.sharetracesdk.ShareTrace;
import cn.net.shoot.sharetracesdk.ShareTraceWakeUpListener;

public class LaunchActivity extends BaseActivity {
    @BindView(R.id.launchImg)
    ImageView launchImg;
    @BindView(R.id.ll_label)
    LinearLayout llLabel;
    private Timer timer = new Timer();
    private int recLen = 5;
    private static final String SKIP_TEXT = "%ds 跳过";
    private String welcome = "";
    @BindView(R.id.iv_launch_label)
    ImageView ivLaunchLabel;
    @BindView(R.id.tv_count_down)
    TextView tvCountDown;
    private ADDataEntity adDataEntity;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_launch;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        if(!this.isTaskRoot()) {
            //判断该Activity是不是任务空间的源Activity，“非”也就是说是被系统重新实例化出来
            //如果你就放在launcher Activity中话，这里可以直接return了
            Intent mainIntent=getIntent();
            String action=mainIntent.getAction();
            if(mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER)
                    && action.equals(Intent.ACTION_MAIN)) {
                finish();
                //finish()之后该活动会继续执行后面的代码，你可以logCat验证，加return避免可能的exception
                return;
            }
        }
        ButterKnife.bind(this);

        initStepService();


        // 获取唤醒参数
        // 确保用户同意《隐私政策》之后，再初始化openinstall SDK；如果用户不同意，则不进行openinstall SDK初始化
        ShareTrace.getWakeUpTrace(getIntent(), wakeUpListener);
        JPushInterface.init(getApplicationContext());
        String regId = JPushInterface.getRegistrationID(this);
        LogUtil.e("regId", regId);
        initPush();
        timer.schedule(task, 1000, 1000);
        welcome = SharePreferenceUtils.getString(this, "WELCOME");

//        initData();
//        int width[] = CommonUtil.getScreenHW(this);
//
//        int ivWidth = (int) Math.round(width[0] * 0.87);
//        int margins = (int) Math.round(width[0] * 0.18);
//        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ivWidth, ViewGroup.LayoutParams.WRAP_CONTENT);
//        layoutParams.setMargins(0, margins, 0, 0);
//        ivLaunchLabel.setLayoutParams(layoutParams);

        AdInfoEntity adInfoEntity = UserAPI.getADInfo();
        if (!TextUtils.isEmpty(UserAPI.getUserId())) {
            if (adInfoEntity != null) {
                if (adInfoEntity.code == 0) {
                    if (adInfoEntity.data != null && adInfoEntity.data.size() > 0) {
                        for (int i = 0; i < adInfoEntity.data.size(); i++) {
                            if (adInfoEntity.data.get(i).positionCode == 1) {
                                adDataEntity = adInfoEntity.data.get(i);
                                ivLaunchLabel.setVisibility(View.GONE);
//                                Glide.with(getApplicationContext()).load(adDataEntity.cover).apply(RequestOptions.bitmapTransform(new FitCenter())).into(new SimpleTarget<Drawable>() {
//                                    @Override
//                                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
//                                        launchImg.setImageDrawable(resource);
//                                    }
//                                });
                                launchImg.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                GlideUtils.loadImage(LaunchActivity.this, adDataEntity.cover, launchImg);
                                break;
                            }
                        }
                        if (adDataEntity == null) {
                            startIntentTo();
                        }
                    }
                }
            } else {
                startIntentTo();
            }
        } else {
            startIntentTo();
        }
    }

    private void initData() {
        /**
         * 判断是否通过了部门审核
         */
        new UserAPI().judgeCheck(new BaseResultCallback<JudgeBranchCheckEntity>() {
            @Override
            public void onResponse(JudgeBranchCheckEntity response) {
                if (response.code == 0) {
                    if (response.data == 1) {
                        Intent intent = new Intent(LaunchActivity.this, InputTeamCodeActivity.class);
                        intent.putExtra("BranchCheck", 1);
                        startActivity(intent);
                        finish();
                    } else if (response.data == 3) {
                        ToastUtils.showShort("请重新选择部门");
                        startActivity(new Intent(LaunchActivity.this, InputTeamCodeActivity.class));
                        finish();
                    } else if (response.data == 0) {
                        startActivity(new Intent(LaunchActivity.this, InputTeamCodeActivity.class));
                        finish();
                    } else if (response.data == 4) {//邀请
                        topId();
                    } else {
                        AppUtils.jumpToMain(LaunchActivity.this);
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(LaunchActivity.this, LoginActivity2.class));
                        finish();
                    }
                } else {
                    UserAPI.clearLogin();
                    startActivity(new Intent(LaunchActivity.this, LoginActivity2.class));
                    finish();
                }
                super.onError(e, body);
            }
        });
    }

    private void topId() {
        showDialog();
        new UserAPI().getTopId(new BaseResultCallback<GetTopIdEntity>() {
            @Override
            public void onResponse(GetTopIdEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    if (!TextUtils.isEmpty(response.data)) {
                        Intent intent = new Intent(LaunchActivity.this, CheckTeamActivity.class);
                        intent.putExtra("companyId", response.data);
                        startActivity(intent);
                        finish();
                    }
                }
            }

            @Override
            public void onError(Throwable e, String body) {
                super.onError(e, body);
                dismissDialog();
            }
        });
    }

    /**
     * 初始化计步服务
     * 注：因初始化需要过程，正常项目中，初始化应该放在进入到主界面之前的activity中，比如闪屏页中进行初始化
     * 因此本demo在第一次安装时会提示"手机暂不支持计步功能"，杀死进程再次打开即可正常显示
     */
    @SuppressLint("WrongConstant")
    private void initStepService() {

        Intent intent = new Intent(this, StepService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(intent);
        } else {
            startService(intent);
        }
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                tvCountDown.setText(String.format(SKIP_TEXT, recLen));
                if (recLen == 0) {
                    startIntentTo();
                }
            }
            return false;
        }
    });

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            recLen--;
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };

    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    private void startIntentTo() {
        if (TextUtils.isEmpty(welcome)) {
            startActivity(new Intent(LaunchActivity.this, WelcomeActivity.class));
//            finish();
        } else {
            if (!UserAPI.checkLogin()) {
                startActivity(new Intent(LaunchActivity.this, LoginActivity2.class));
//                finish();
            } else {
                startActivity(new Intent(LaunchActivity.this, MainActivity.class));
//                initData();
            }
        }
        finish();
        timer.cancel();
    }

    private ShareTraceWakeUpListener wakeUpListener = new ShareTraceWakeUpListener() {
        @Override
        public void onWakeUp(AppData data) {
            Log.e("sharetrace", "appData=" + (data == null ? null : data.toString()));
        }
    };

    private void showWakeUpDialog(String data) {
        if (TextUtils.isEmpty(data)) return;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("OpenInstall");
        builder.setMessage("这是App被拉起获取的数据\n" + data);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 此处要调用，否则App在后台运行时，会无法获取
        // 应用在后台被调起来时获取一键调起参数
        ShareTrace.getWakeUpTrace(intent, wakeUpListener);
    }

    /**
     * 初始化jpush推送
     */
    @SuppressLint("MissingPermission")
    private void initPush() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        JPushInterface.setAlias(getApplicationContext(), 0, DeviceUtils.getDeviceId());
        Set<String> strings = new HashSet<>();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LogUtil.e("别名", DeviceUtils.getDeviceId());
//        SharePreferenceUtils.putString(this,"RegId",DeviceUtils.getDeviceId());
        strings.add(DeviceUtils.getDeviceId());
        JPushInterface.setTags(getApplicationContext(), 0, strings);
    }

    @Override
    protected void onResume() {
//        isForeground = true;
        super.onResume();
        JPushInterface.resumePush(getApplicationContext());
    }


    @Override
    protected void onPause() {
//        isForeground = false;
        super.onPause();
    }


    @Override
    protected void onDestroy() {
//        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    @OnClick({R.id.launchImg, R.id.tv_count_down})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.launchImg:
                if (adDataEntity != null) {
                    startIntentTo();
                    ADToWebOrActivityUtil.toType(this, adDataEntity);
                }
                break;
            case R.id.tv_count_down:
                startIntentTo();
                break;
        }
    }
}
